package com.czy.blog.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czy.blog.entity.Role;
import com.czy.blog.entity.User;
import com.czy.blog.service.RoleService;
import com.czy.blog.service.UserService;
import com.czy.blog.utils.JsonMapper;
import com.czy.blog.vo.PageVo;
import com.czy.blog.vo.RoleVo;
import com.czy.blog.vo.UserVo;

/** 用户管理控制层 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController
{
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	/** 进入用户管理主页面 */
	@RequestMapping("/main")
	public String main()
	{
		return "/user/user_main";
	}

	@RequestMapping("/getPage")
	@ResponseBody
	public String getPage(Model model,String username,PageVo pageVo)
	{
		Page<User> users = userService.findByUsernameLike(username,pageVo);
		return generalDataGridJson(users.getTotalElements(), users2Vos(users));
	}

	/**
	 * List<User>  -->  List<UserVo>
	 * @param users
	 */
	private List<UserVo> users2Vos(Page<User> users)
	{
		List<UserVo> vos = new ArrayList<UserVo>();
		for (User user : users)
		{
			UserVo vo = new UserVo();
			BeanUtils.copyProperties(user, vo);
			vo.setCz(user.getId());
			vos.add(vo);
		}
		return vos;
	}

	/**  保存用户 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(Model model, User user)
	{
		userService.save(user);
		return "success";
	}

	@RequestMapping("/findOne/{id}")
	@ResponseBody
	public String findOne(Model model, @PathVariable String id)
	{
		User user = userService.findById(id);
		UserVo vo = new UserVo();
		BeanUtils.copyProperties(user, vo);
		String json = new JsonMapper().toJson(vo);
		return json;
	}
	
	/**  弹出用户设置角色页面  */
	@RequestMapping("/getRoles/{userId}")
	public String getRoles(Model model,@PathVariable String userId)
	{
		//查询所有角色，标记当前用户已拥有的角色（默认选中）
		List<Role> roles = roleService.findAll(); 
		List<Role> ownRoles = roleService.findRolesByUserId(userId);
		List<RoleVo> vos = new ArrayList<RoleVo>();
		
		for(Role role : roles){
			RoleVo vo = new RoleVo();
			BeanUtils.copyProperties(role, vo);
			if(ownRoles.contains(role)){
				vo.setSelected(true);
			}
			vos.add(vo);
		}
		
		model.addAttribute("roles", vos);
		return "/user/user_setRole";
	}
	
	/**
	 * 设置用户角色
	 * @param userId  带设置角色的用户ID
	 * @param roleIds 角色ID集合
	 */
	@RequestMapping("/setRoles")
	@ResponseBody
	public String setRoles(Model model,String userId,String[] roleIds)
	{
		userService.setRoles(userId,Arrays.asList(roleIds));
		return "sucess";
	}
	
	/** 弹出新建用户页面  */
	@RequestMapping("/add")
	public String add(Model model)
	{
		model.addAttribute("user", new User());
		model.addAttribute("action", "save");
		return "/user/user_edit";
	}
	
	/** 弹出编辑用户页面 */
	@RequestMapping("/edit/{userId}")
	public String edit(Model model,@PathVariable String userId)
	{
		User user = userService.findById(userId);
		model.addAttribute("user", user);
		model.addAttribute("action", "update");
		return "/user/user_edit";
	}
	
	/**更新用户*/
	@RequestMapping("/update")
	@ResponseBody
	public String update(Model model,@ModelAttribute("updateObj") User user)
	{
		userService.update(user);
		return "success";
	}
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 表单请求参数bind=true才执行，仅对update()有效（提交请求中不包含password, registerDate, salt, roles属性值，须预绑定到model）
	 */
	@ModelAttribute
	public void prepare(@RequestParam(defaultValue = "false") Boolean bindable, String id, Model model) {
		if (bindable) {
			model.addAttribute("updateObj", userService.findById(id));
		}
	}
	
	/**
	 * 批量删除
	 * @param ids  待删除记录ID集合
	 */
	@RequestMapping("/batchDelete")
	@ResponseBody
	public String batchDelete(Model model, String[] ids) {
		userService.delete(Arrays.asList(ids));
		return "success";
	}

	public UserService getUserService()
	{
		return userService;
	}

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}

}
